package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class Auth extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Auth() {
        super();
    }
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String userId = request.getParameter("userID");
		String password = request.getParameter("password");
		ArrayList<Qr> qrs = new ArrayList<Qr>();
		Qr qr = new Qr();
		/* 
		 *		1 比對身份成功且有權限
		 *		2 比對身份失敗
		 *	 	3 無任何權限
		 * */

		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/jason");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String strSQL = "SELECT userid,pwd,username,issuperuser FROM personnel WHERE userid=? AND pwd=?";
		String errPars = "}";
		
		try {
			conn = wid.getConn(true);
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, userId);
			ps.setString(2, password);
			rs = ps.executeQuery();
			
			boolean isMatch = rs.next()?true:false;
			if (isMatch) { //表示輸入的User存在
				qr.setStatus("1");	//比對身份成功
				qr.setPwd(rs.getString("pwd"));
				qr.setUserId(rs.getString("userid"));
				qr.setUserName( wid.DB2UI( rs.getString("username"),conn.getMetaData().getDatabaseProductName() ) );
				qr.setSU( "t".equalsIgnoreCase( rs.getString("issuperuser") ) );
				
				strSQL = "SELECT sysval FROM envparams WHERE sysattr=1";
				ps = conn.prepareStatement(strSQL);
				rs = ps.executeQuery();
				rs.next();
				qr.setReDepQueryFrame( rs.getInt("sysval") );
				
				if ( !qr.isSU() ) {
					strSQL = "SELECT DISTINCT subsysid FROM mproleuser WHERE bssid=? AND userid=? AND roleid=?";
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, "MBMS" );
					ps.setString(2, userId );
					ps.setInt(3, wid.CURMAINTAINROLE );
					rs = ps.executeQuery();
					while ( rs.next() ) {
						qr.setSubsysList( qr.getSubsysList() + wid.splitTokenONE + rs.getString("subsysid") );
					}
					if ( qr.getSubsysList().contains( wid.splitTokenONE ) ) {
						qr.setSubsysList( qr.getSubsysList().substring(wid.splitTokenONE.length(), qr.getSubsysList().length()) );	
					}
				}
			} else {
				qr.setStatus("User ID 或 Password 不存在！");
			}
		} catch (SQLException e) {
			String errorMessage = "出問題\n\n"+wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
			qr.setStatus("{\"errorMsg\":\""+errorMessage+"\"}");
		} catch ( Exception e) {
			String errorMessage = "出問題\n\n"+wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
			qr.setStatus("{\"errorMsg\":\""+errorMessage+"\"}");
		}finally {
			try {
				if ( rs!= null ) { rs.close(); }
				if ( ps!= null ) { ps.close(); }
				if ( conn!= null ) { conn.close(); }
			} catch (SQLException e) {
				qr.setStatus(e.toString());
			}
		}
		qrs.add(qr);
		
		response.getWriter().write(new Gson().toJson(qrs));
	}
}